package com.jie.gateway.service;

import cn.hutool.json.JSONUtil;
import com.jie.component.init.base.AbstractApplicationPostConstructHandler;
import com.jie.model.redis.gateway.ApiRestrictData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author jie
 * @version 1.0 2025-02-16
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApiRestrictCacheOperate extends AbstractApplicationPostConstructHandler {

    private final StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<String> redisScript;


    @Override
    public Integer executeOrder() {
        return 0;
    }

    @Override
    public void executeInit(ConfigurableApplicationContext context) {
        try {
            redisScript = new DefaultRedisScript<>();
            redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/apiLimit.lua")));
            redisScript.setResultType(String.class);
        } catch (Exception e) {
            log.error("redisScript init lua error", e);
        }
    }

    public ApiRestrictData apiRuleOperate(List<String> keys, Object[] args) {
        String o = stringRedisTemplate.execute(redisScript, keys, args);
        return JSONUtil.toBean(o, ApiRestrictData.class);
    }
}
